<template>
  <div>
    <div class="head">
      <img
        src="@/assets/css/images/ownFile.png"
        alt=""
        style="width: 45px; height: 45px; vertical-align: middle"
      />
      <b> 个人文件</b>
      <br /><br />
      <el-button>新建 </el-button>
      <el-button
        type="primary"
        @click="uploadShow()"
        style="margin-right: 10px"
      >
        <i class="el-icon-upload"></i>上传
      </el-button>
      <!-- 上传选项 -->
      <el-dialog :visible.sync="a" title="文件上传">
        <uploader
          :options="options"
          class="uploader-example"
          :limit="3"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          multiple
          @files-added="handleFilesAdded"
        >
          <uploader-unsupport></uploader-unsupport>
          <p>温馨提示：可将文件拖动到灰色区域上传</p>
          <uploader-drop>
            <uploader-btn style="margin-right:10px;border-radius:5px"
              >上传文件</uploader-btn
            >
            <uploader-btn :directory="true" style="border-radius:5px"
              >上传文件夹</uploader-btn
            >
          </uploader-drop>
          <uploader-list v-show="panelShow">
            <template v-slot:default="props">
              <div class="file-panel">
                <div class="file-title">
                  <span class="title-span">
                    上传列表<span class="count"
                      >（{{ props.fileList.length }}）</span
                    >
                  </span>
                </div>
                <!-- 正在上传的文件列表 -->
                <el-collapse-transition>
                  <ul class="file-list" v-show="!collapse">
                    <li
                      class="file-item"
                      :class="{ 'custom-status-item': file.statusStr !== '' }"
                      v-for="file in props.fileList"
                      :key="file.id"
                    >
                      <uploader-file ref="fileItem" :file="file" :list="true">
                      </uploader-file>
                      <!-- 自定义状态 -->
                      <span class="custom-status">{{ file.statusStr }}</span>
                    </li>
                    <div class="no-file" v-if="!props.fileList.length">
                      <i class="icon-empty-file"></i> 暂无待上传文件
                    </div>
                  </ul>
                </el-collapse-transition>
              </div>
            </template>
          </uploader-list>
        </uploader>
      </el-dialog>
      <!-- 拖拽上传 -->
      <el-dialog
        :visible.sync="uploadDlg"
        width="40%"
        style="text-align: center"
      >
        <el-upload
          class="upload"
          drag
          action="http://192.168.43.79:8080/userFile/upload"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-dialog>
      <el-button
        type="danger"
        style="display: none/block"
        id="dbtn"
        class="batchDelete"
        @click="batchDelete()"
        >批量删除</el-button
      >
    </div>
    <br />
    <el-card class="mycard" style="height: 740px">
      <el-row>
        <!-- 搜索框 -->
        <el-input
          placeholder="请输入内容"
          clearable
          v-model="queryInfo.query"
          @clear="getMyFileList"
          style="width:350px;float:right"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getMyFileList"
          ></el-button>
        </el-input>
        <!-- 表格展示 -->
        <el-table
          :data="tableData"
          style="width: 100%"
          ref="multipleTable"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @current-change="handleCurrentChange"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="name" label="名称" sortable>
            <template slot-scope="scope" class="rowText">
              <div class="icon">
                <!-- <img
                  class="fileimg"
                  :src= fileimg(scope.row.filetype)
                  alt=""
                /> -->
                <svg class="icons" aria-hidden="true">
                  <use v-bind:xlink:href="scope.row.icon"></use>
                </svg>
              </div>
              <div class="text">
                <b
                  class="rowname"
                  @click="preview(scope.row)"
                  style="margin-left:5px"
                  > {{ scope.row.name }}</b
                >
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="date" label="修改时间" sortable width="280">
          </el-table-column>
          <el-table-column prop="fileType" label="类型" sortable width="180">
          </el-table-column>
          <el-table-column prop="storage" label="大小" sortable width="220">
          </el-table-column>
          <!-- 操作按钮 -->
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                @click="handleEdit(scope.$index, scope.row)"
                icon="el-icon-edit"
                circle
                plain
              ></el-button>
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                @click.native.prevent="deleteRow(scope.$index)"
                circle
              ></el-button>
              <el-button
                type="success"
                plain
                icon="el-icon-share"
                circle
                @click="getShareLink(scope.$index, scope.row)"
              ></el-button>
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                @click="download(scope.row.name)"
                circle
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <br />
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[6, 10, 15]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        >
        </el-pagination>
      </el-row>
    </el-card>
    <!-- 编辑 -->
    <el-dialog
      title="文件重命名"
      :visible.sync="editFormVisible"
      :close-on-click-modal="false"
      class="edit-form"
      center
    >
      <el-form :model="editForm" label-width="80px" ref="editForm">
        <el-form-item label="名称" prop="Name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
          <el-input
            v-model="editForm.date"
            auto-complete="off"
            :disabled="true"
          ></el-input>
          <el-input
            v-model="editForm.storage"
            auto-complete="off"
            :disabled="true"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取 消 </el-button>
        <el-button type="primary" @click.native="handleUpdate('editForm')"
          >确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 外链设置 -->
    <el-dialog title="文件分享" :visible.sync="dialogShareFormVisible" center>
      <el-form :model="form" ref="form">
        <el-form-item
          label="链接有效期至："
          :rules="{
            required: true,
          }"
        >
          <el-col :span="11" class="timeCol">
            <el-date-picker
              v-model="shareDate"
              align="right"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="是否设置提取码：">
          <el-radio v-model="radio" label="1">是</el-radio>
          <el-radio v-model="radio" label="2">否</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createShareLink" round plain
          >生成链接</el-button
        >
      </div>
      <div slot="footer">
        <small>tips: 若分享的文件是视频或音频,有效期仅为一小时</small>
      </div>
    </el-dialog>
    <!-- 外链生成 -->
    <el-dialog
      title="分享链接"
      :visible.sync="shareLinkDialog"
      center
      :close-on-click-modal="false"
      @opened="ShowQRCode()"
      ><img
        src="@/assets/css/images/fileShare.svg"
        @click="goShare"
        class="shareButton"
        alt=""
      />
      <el-form :model="form" ref="form">
        <el-form-item label="分享链接：" :label-width="formLabelWidth">
          <el-input v-model="form"> </el-input>
        </el-form-item>
        <el-form-item
          label="提取码："
          :rules="[{ type: 'number', message: '提取码必须为数字值' }]"
        >
          <el-input type="textarea" v-model="code"></el-input>
        </el-form-item>
        <el-form-item label="外链二维码:"> </el-form-item>
      </el-form>
      <div id="qrcode" style="margin-left:42%"></div>
      <!-- tips -->
      <div slot="footer">
        <small>tips: 有效期至截止日期当天23:59:59</small>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="videoDialog" style="">
      <video
        :src="videoSrc"
        controls="controls"
        width="100%"
        height="100%"
        style="border-radius:10px"
      ></video>
    </el-dialog>
  </div>
</template>

<script>
import PreviewFile from "../../PreviewFile.vue";
import QRCode from "qrcodejs2";
const axios = require("axios");
export default {
  components: {
    PreviewFile, //组件注册
  },
  data() {
    return {
      options: {
        target: `http://192.168.43.79:8080/userFile/upload`, // 后台接口
        chunkSize: 1024 * 1024, //  每个分片的大小
        fileParameterName: "file", //  上传文件时文件的参数名，默认 file
        maxChunkRetries: 3, //  并发上传数，默认 3
        testChunks: true, //  是否开启分片已存在于服务器的校验
        // 服务器分片校验函数，秒传及断点续传基础
        // checkChunkUploadedByResponse: function (chunk, message) {
        // 	let objMessage = JSON.parse(message)
        // 	if (objMessage.success) {
        // 		let data = objMessage.data
        // 		if (data.skipUpload) {
        // 			// 分片已存在于服务器中
        // 			return true
        // 		}
        // 		return (data.uploaded || []).indexOf(chunk.offset + 1) >= 0
        // 	} else {
        // 		console.log(objMessage.message)
        // 		return true
        // 	}
        // },
        query() {},
      },
      videoSrc: "",
      videoDialog: false,
      //时间选择器配置
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
        shortcuts: [
          {
            text: "当天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "1天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "7天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
          {
            text: "14天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 14);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      radio: "2",
      //文件上传状态
      fileStatusText: {
        success: "上传成功",
        error: "error",
        uploading: "上传中",
        paused: "暂停中",
        waiting: "等待中",
      },
      multipleSelection: [],
      //表格数据
      tableData: [
        {
          id: "1",
          date: "2022-05-02",
          name: "Resource_Systems.pdf",
          fileType: "pdf",
          storage: "2568KB",
          icon: "#icon-pdf",
        },
        {
          id: "2",
          date: "2022-03-04",
          name: "毕业设计开题报告.doc",
          fileType: "doc",
          storage: "168KB",
          icon: "#icon-WORD"
        },
        {
          id: "3",
          date: "2022-03-01",
          name: "毕业实习报告.pdf",
          fileType: "pdf",
          storage: "68KB",
          icon: "#icon-pdf",
        },
        {
          id: "4",
          date: "2022-04-03",
          name: "compressed_tracemonkey.pdf",
          fileType: "pdf",
          storage: "1648KB",
          icon: "#icon-pdf",
        },
        {
          id: "5",
          date: "2022-03-13",
          name: "2022毕业设计相关文档模板.zip",
          fileType: "zip",
          storage: "708KB",
          icon: "#icon-yasuobao",
        },
        {
          id: "6",
          date: "2022-04-01",
          name: "movie.mp4",
          fileType: "mp4",
          storage: "168KB",
          src: "https://www.runoob.com/try/demo_source/movie.mp4",
          icon: "#icon-shipin",
        },
      ],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      total: 6, //TODO默认0
      form: {
        name: "",
        code: "",
      },
      //提取码
      code: "",
      editForm: {
        name: "",
        date: "",
        storage: "",
        index: 0,
      },
      //有效期
      shareDate: "",
      //定义属性
      name: undefined,
      date: undefined,
      storage: undefined,
      editFormVisible: false,
      //生成分享链接
      dialogShareFormVisible: false,
      uploadDialog: false,
      panelShow: false,
      uploadDlg: false,
      //分享链接
      shareLinkDialog: false,
    };
  },
  mounted() {
    // this.qrcode();
    this.fileimg();
  },
  created() {
    this.tableData.map((i) => {
      i.show = false;
      return i;
    });
    //TODO
    // this.getMyFileList();
  },
  methods: {
    fileimg(type) {
      if (type == "pdf") {
        return "@/assets/css/images/pdf.svg";
      }
    },
    handleEdit: function(index, row) {
      this.editFormVisible = true; //dialog对话窗口打开
      this.editForm = Object.assign({}, row); //将数据传入dialog页面
      this.editForm.index = index; //传递当前index
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    deleteRow(index) {
      this.total--;
      this.tableData.splice(index, 1);
      this.$message({
        type: "success",
        message: "删除成功，可在回收站查看!",
      });
    },
    getBigectURL(event) {
      this.videoDialog = true;
      console.log("getBigectURL", event);
      var current = event.target.files[0];
      var fileReader = new FileReader();
      fileReader.readAsDataURL(current);
      var that = this;
      fileReader.onload = function(e) {
        that.videoSrc = e.currentTarget.result;
      };
    },
    //获取文件列表数据
    async getMyFileList() {
      const { data: res } = await this.$http.get("myfile", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取文件列表失败！");
      }
      this.$message.success("获取文件列表成功！");
      //更新列表数据
      this.tableData = res.data;
      this.total = res.data.total;
    },
    // handleCancel(formName) {
    //   this.editFormVisible = false;
    // },
    handleUpdate(formName) {
      //dialog页面数据写入到tableData页面上
      //this.$set(tableName,talbeIndex,data)
      this.$set(this.tableData, this.editForm.index, {
        name: this.editForm.name,
        date: this.editForm.date,
        storage: this.editForm.storage,
      });
      this.editFormVisible = false;
      this.$message({
        type: "success",
        message: "文件重命名成功",
      });
    },
    handleSelectionChange(val) {
      var deletebtn = document.getElementById("dbtn");
      deletebtn.style.opacity = 1;
      this.multipleSelection = val;
    },
    //TODO文件损坏
    download(item) {
      axios({
        url: "http://localhost:8080/static/pdf/web/viewer.html?file=" + item,
        method: "GET",
        responseType: "blob",
        headers: {
          "Content-Type": "application/json; application/octet-stream",
        },
      }).then((response) => {
        var fileUrl = window.URL.createObjectURL(new Blob([response.data]));
        var fileLink = document.createElement("a");
        fileLink.href = fileUrl;

        fileLink.setAttribute("download", item);
        document.body.appendChild(fileLink);

        fileLink.click();
        URL.revokeObjectURL(fileUrl);
        // resolve(response);
      });
    },
    createShareLink() {
      // console.log(this.shareDate.getTime());
      if (this.shareDate != "") {
        this.dialogShareFormVisible = false;
        setTimeout(() => {
          this.shareLinkDialog = true;
          this.$message.success("链接生成成功,有效期至" + this.shareDate);
        }, 500);
      } else {
        this.$message.error("请设置外链有效期！");
      }
      //随机生成提取码
      if (this.radio == 1) {
        var code = "";
        for (var i = 0; i < 6; i++) {
          var radom = Math.floor(Math.random() * 10);
          code += radom;
        }
        this.code = code;
      } else {
        this.code = "";
      }
    },
    batchDelete() {
      for (let i = 0; i < this.tableData.length; i++) {
        const element = this.tableData[i];
        element.id = i;
      }
      if (this.multipleSelection.length == 0)
        this.$message.error("请先至少选择一项");
      else {
        this.$confirm("此操作会删除这些文件, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.multipleSelection.forEach((element) => {
              this.tableData.forEach((e, i) => {
                if (element.id == e.id) {
                  this.tableData.splice(i, 1);
                }
              });
            });
            this.$message({
              type: "success",
              message: "批量删除成功，可在回收站查看!",
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },
    handleFilesAdded() {
      this.panelShow = true;
    },
    // 加载二维码
    ShowQRCode() {
      document.getElementById("qrcode").innerHTML = "";
      // this.qrcode = this.$QRCode();
      let qrcode = new QRCode("qrcode", {
        width: 132,
        height: 132,
        text: "https://www.baidu.com", // 二维码地址
      });
    },

    // 提交删除用户
    // submitDeleteUser() {
    //   // this.deleteMenuFormVisible = false;
    //   let param = {
    //     token: this.$store.state.token,
    //     name: this.tableData,
    //   };
    //   //clientDelete为接口
    //   clientDelete(param).then((res) => {
    //     if (res.data.respCode == "200") {
    //       this.$message.success(res.data.respDesc);
    //     } else {
    //       this.$message.error(res.data.respDesc);
    //     }
    //     this.reload();
    //   });
    // },
    uploadShow(rootFile, file, response) {
      this.uploadDlg = true;
      if (response == "") {
        file.statusStr = "上传失败";
        this.callback(false);
        return;
      }
      // let result = JSON.parse(response)
      // if (result.success) {
      // 	file.statusStr = ''
      // 	if (this.filesLength === 1) {
      // 		// 本次所有的文件均已上传完毕
      // 		this.$message.success(`上传完毕`)
      // 		this.serviceEl.$emit('getTableDataByType')
      // 		this.serviceEl.$store.dispatch('showStorage')
      // 		this.callback(true)
      // 	}
      // } else {
      // 	this.$message.error(result.message)
      // 	file.statusStr = '上传失败'
      // }
      // this.filesLength--
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    preview(row) {
      if (row.name.substring(row.name.length - 3) == "mp4") {
        this.videoDialog = true;
        this.videoSrc = row.src;
      } else if (row.name.substring(row.name.length - 3) == "doc") {
        window.open("https://docs.qq.com/doc/DVHdnVUx3eUtVd25r");
        // url为该文件在服务器的地址
        // window.open(" https://view.officeapps.live.com/op/view.aspx?src=" + url)
      } else {
        window.open("/static/pdf/web/viewer.html?file=" + row.name);
      }
    },
    goShare() {
      // const routeUrl = this.$router.resolve({
      //   name: 'sharePage',
      //   params: { code:this.code}
      // });
      // window.open(routeUrl.href, "_blank");
      var { href } = this.$router.resolve({
        name: "sharePage",
      });
      localStorage.setItem("code", this.code);
      localStorage.setItem("time", this.shareDate.getTime());
      window.open(href);
    },
    getShareLink: function(index, row) {
      this.dialogShareFormVisible = true; //dialog对话窗口打开
      var url = Object.assign({}, row);
      var fileurl = "http://localhost:8080/static/pdf/web/viewer.html?file=";
      // var fileurl = "http://localhost:8080/sharePage"
      this.form = fileurl + url.name; //将数据传入dialog页面
      // console.log(url)
    },
  },
};
</script>

<style lang="less" scoped>
// .fileimg {
//   width: 35px;
//   height: 32px;
// }
.rowText {
  display: table-cell;
  text-align: center;
}

.icons {
  width: 35px;
  height: 32px;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.icon,
.text {
  display: table-cell;
  vertical-align: middle;
  margin-right: 5px;
}
.opbutton {
  display: table-cell;
  vertical-align: middle;
  margin-right: 15px !important;
}
.share {
  opacity: 1;
  display: table-cell;
  vertical-align: middle;
  > .shareimg {
    width: 25px;
    height: 30px;
  }
}
// .share:hover{
//   opacity: 1;
// }
.svg {
  width: 100px;
}
.dialog-footer {
  margin-bottom: 20px;
  margin-top: -40px;
}
.rowname {
  cursor: pointer;
}
.shareButton {
  width: 20px;
  height: 30px;
  margin-left: 95%;
  margin-bottom: -20px;
  cursor: pointer;
  z-index: 999;
}
.batchDelete {
  opacity: 0;
}
.batchDelete1 {
  opacity: 1;
}
.timeCol {
  width: 230px;
}
.line {
  width: 5px;
}
/deep/ .el-dialog {
  border-radius: 8px;
}
.uploadbtn {
  background-color: white;
  border: none;
  color: black;
  width: 100%;
  font-size: 14px;
  text-align: center;
}
.uploadbtn:hover {
  background-color: rgb(235, 247, 252);
  color: rgb(89, 193, 235);
}
</style>
